<!--
//
// GDictSelect.vue
// hs-admin
//
// Created by 区区电脑 on 2023/07/22.
//
-->
<template>
    <el-select v-model="value" :placeholder="placeholder" filterable clearable style="width: 100%">
        <el-option v-for="item in state.list" :key="item.code" :label="item.name" :value="item[valueField]"/>
    </el-select>
</template>

<script setup>
import {ref, reactive, computed, onMounted, watch} from "vue";

const props = defineProps({
    modelValue: {
        type: [String, Number, Boolean]
    },
    code: {
        type: String
    },
    placeholder: {
        type: String
    },
    useDefault: {
        type: Boolean,
        default: () => false
    },
    valueField: {
        type: String,
        default: () => "code"
    }
});
const emits = defineEmits(["update:modelValue", "change"]);

const value = ref(null);
const state = reactive({
    list: []
});

// 统一字典查询入口
function getDictDataList(code) {
    state.list = $getDictDataListWithTypeCode(code)
    if (!props.modelValue && state.list[0] && props.useDefault) {
        // 没有值的时候设置默认值
        value.value = state.list[0][props.valueField]
        updateValue()
    }
}

function setValue() {
    value.value = props.modelValue;
}

function updateValue() {
    emits("update:modelValue", value.value)
    emits("change", state.list.find(item => item[props.valueField] === value.value))
}

watch(() => props.modelValue, () => {
    setValue();
})
watch(() => value.value, (value, oldValue) => {
    if (value || oldValue) {
        updateValue()
    }
})

onMounted(() => {
    getDictDataList(props.code)
    setValue();
})
</script>

<style lang="scss" scoped>
.GDictSelect {
}
</style>
